package Boot.test.Utils;

import Boot.test.Dao.ServerBook;
import Boot.test.Domain.two;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.socket.server.standard.SpringConfigurator;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
//不能使用aop切面注解，其中 @Transactional和@Async注解都包含了AOP
@Component
@ServerEndpoint(value = "/websocket/{myWebsocket}")
public class WebsocketController {

    @Autowired
    public static ServerBook bookDao;
    public static Map<String, Session> SessionC =
            new HashMap<String, Session>();


    //与某个客户端的连接会话，需要通过它来给客户端发送数据
    private Session WebSocketsession;

    String myWebsocket = "";

    /**
     * 连接建立成功调用的方法
     *
     * @param myWebsocket
     */
    @OnOpen
//    public void onOpen(@PathParam("myWebsocket") String myWebsocket, Session session){
    public void onOpen(@PathParam("myWebsocket") String myWebsocket, Session session) {
        List<two> all = null;
        try {
            all = bookDao.findAll();
        } catch (Exception e) {
            System.out.println(e);
        }
        System.out.println(all);
        SessionC.put(myWebsocket, session);
    }

    /**
     * 收到客户端消息时触发
     *
     * @param myWebsocket
     * @param message
     * @return
     */
    @OnMessage
    public void onMessage(@PathParam("myWebsocket") String myWebsocket, String message) throws IOException {


//        sendMessage(myWebsocket, message);


    }

    /**
     * 异常时触发
     *
     * @param myWebsocket
     * @param throwable
     */
    @OnError
    public void onError(@PathParam("myWebsocket") String myWebsocket, Throwable throwable) {

    }

    /**
     * 关闭连接时触发
     *
     * @param myWebsocket
     */
    @OnClose
    public void onClose(@PathParam("myWebsocket") String myWebsocket) {
//        Token token = new Token();
//        String token1 = token.getToken(myWebsocket);
        // 用户退出时删除
//        SessionC.remove(token1);

    }

    public void sendMessage(String myWebsocket, String message) throws IOException {

//        Session session = SessionC.get(myWebsocket);
//        session.getBasicRemote().sendText("111");
    }




}